<?php


namespace app\controller;


use support\bootstrap\Redis;

class Qywx
{
    /**
     * 微信授权登录
     *
     * */
    private $appId = 'wwd51800cfc7708391';//我的企业ID
    private $appSecret = '-IIxJtIMrZgflsi-9gZUrbC7Pt1LmbgjqnaPzGEe9QA';//自建应用里的Secret
    private $agentid = '1000005';//AgentId 手动授权时scope值改为snsapi_privateinfo 后面必须有AgentId
    private $common_url = 'http://liubao.org.cn';
    private $code = '';
    public  $access_token = '';
    private $user_ticket = '';
    private $UserId = '';
    private $openid = '';

    public function index()
    {
        $uri = urlencode($this->common_url . '/Qywx/back'); //授权成功返回地址
        //下面$url请求授权登录地址,设置的是手动授权
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $this->appId . '&redirect_uri=' . $uri . '&response_type=code&scope=snsapi_privateinfo&agentid=' . $this->agentid . '&state=STATE#wechat_redirect';
        return redirect($url);
    }

    public function back($request)
    {
        $this->code = $request->get('code'); //接收上面url返回code，5分钟有效期
        try {
            $userInfo = $this->common();
            if (isset($userInfo)) {
                //$openId = $this->getOpenId();//获取openID（——暂时不用）
                return $userInfo;
            }
        } catch (\Exception $e) {
            return false;
        }
    }

    //获取企业微信用户信息
    public function common()
    {
        $access_token = $this->getAccessToken();//获取token
        $user_ticket = $this->getUserInfoList();//获取基本信息里的user_ticket值
        $userInfo = $this->getUserInfoDetail();//获取登录人的详情信息
        if (isset($access_token) && isset($user_ticket) && isset($userInfo)) {
            return json($userInfo);
        }
        return false;
    }

    //获取access_token // 这里可以每过2小时主动去获取一次access_token
    public function getAccessToken()
    {
        if (Redis::get('access_token')) return Redis::get('access_token');
        $code_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" . $this->appId . "&corpsecret=" . $this->appSecret;
        $access_token_str = $this->curl_get($code_url);
        $access_token_list = json_decode($access_token_str, true);
        $this->access_token = $access_token_list["access_token"];//获取access_token
        if ($access_token_list['errcode'] == 0) {
            Redis::set('access_token', $this->access_token, 3600 * 2 - 10);
            return $this->access_token;
        }
        return false;
    }

    //获取登录人基本信息
    public function getUserInfoList()
    {
        $user_url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=" . $this->getAccessToken() . "&code=" . $this->code;
        $userInfo_str = $this->curl_get($user_url);
        $userInfo_list = json_decode($userInfo_str, true);//get获取企业登录人基本信息
        $this->user_ticket = $userInfo_list['user_ticket'];
        $this->UserId = $userInfo_list['UserId'];
        if ($userInfo_list['errcode'] == 0) {
            return $userInfo_list;
        }
        return false;
    }

    //获取登录人的详情信息包括昵称邮箱和头像等
    public function getUserInfoDetail()
    {
        $detail_url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserdetail?access_token=" . $this->getAccessToken();//post获取详细信息
        $param = array('user_ticket' => $this->user_ticket);
        $data = json_decode($this->curl_post($detail_url, $param), true);
        if ($data['errcode'] == 0) {
            return $data;
        }
        return false;
    }

    //根据userID获取openID
    public function getOpenId()
    {
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_openid?access_token=" . $this->getAccessToken();
        $param = array('userid' => $this->UserId);
        $data = json_decode($this->curl_post($url, $param), true);
        if ($data['errcode'] == 0) {
            $this->openid = $data['openid'];
        }
        return $this->openid;
    }

    /**
     * 文本消息推送
     * touser、toparty、totag不能同时为空
     * touser 成员ID列表（消息接收者，多个接收者用‘|’分隔，最多支持1000个）。特殊情况：指定为@all，则向该企业应用的全部成员发送
     * toparty 部门ID列表，多个接收者用‘|’分隔，最多支持100个。当touser为@all时忽略本参数
     * totag 标签ID列表，多个接收者用‘|’分隔，最多支持100个。当touser为@all时忽略本参数
     * safe 表示是否是保密消息，0表示否，1表示是，默认0
     * @param $touser
     * @param $toparty
     * @param string $message //推送内容
     * @return true or false
     */
    public function push_message($touser, $toparty, $message)
    {
        $url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" . $this->getAccessToken();
        $params = array("touser" => $touser, "toparty" => $toparty, "totag" => "", "msgtype" => "text", "agentid" => $this->agentid, "text" => array("content" => $message), "safe" => 0);
        $data = json_decode($this->curl_post($url, $params), true);
        if ($data['errcode'] == 0) {
            return true;
        }
        return false;
    }

    /**
     * //发送推送文本卡片消息展现
     * @param $touser
     * @param $toparty
     * @param $title
     * @param $description
     * @param $url
     * @return bool|mixed
     */
    public function push_card($touser, $toparty, $title, $description, $url)
    {
        $access_token = $this->getAccessToken();
        $push_url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" . $access_token;
        $params = array("touser" => $touser, "toparty" => $toparty, "totag" => "", "msgtype" => "textcard", "agentid" => $this->agentid, "textcard" => array("title" => $title, "description" => $description, "url" => $url, "btntxt" => ""));
        $data = json_decode($this->curl_post($push_url, $params), true);
        if ($data['errcode'] == 0) {
            return $data;
        }
        return false;

    }

    /**
     * 获取部门列表
     * @param $department_id //部门id。获取指定部门及其下的子部门。 如果不填，默认获取全量组织架构
     * @return
     */
    public function get_department($department_id)
    {
        $url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=" . $this->getAccessToken() . "&id=" . $department_id;
        $departmentInfo = $this->curl_get($url);
        $departmentInfo = json_decode($departmentInfo, true);//只能拉取token对应的应用的权限范围内的部门列表
        if ($departmentInfo['errcode'] == 0) {
            return $departmentInfo['department'];//所有的部门信息
        }
        return false;

    }

    // 获取客户列表
    public function externalcontact_list()
    {
        if (Redis::get('userid')) return json_decode(Redis::get('userid'), true);
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/list?access_token=' . $this->getAccessToken() . '&userid=LiuBao';
        $data = json_decode($this->curl_get($url), true);
        if ($data['errcode'] == 0) {
            Redis::set('userid', json_encode($data['external_userid']));
            return $data['external_userid'];
        }
        return false;
    }

    // 添加企业群发消息任务
    public function add_msg_template()
    {
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_msg_template?access_token=' . $this->getAccessToken();
        $params = [
            "chat_type" => "single",
            "external_userid" => $this->externalcontact_list(),
            "sender" => "LiuBao",
            "text" => ["content" => "测试一下"]
        ];
        $data = json_decode($this->curl_post($url, $params), true);
        if ($data['errcode'] == 0) {
            Redis::set('msgid', $data['msgid']);
            return $data;
        }
        return false;
    }

    // 获取企业群发消息发送结果
    public function externalcontact_get_group_msg_result()
    {
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_group_msg_result?access_token=' . $this->getAccessToken();
        $params = ["msgid" => Redis::get('msgid')];
        $data = json_decode($this->curl_post($url, $params), true);
        if ($data['errcode'] == 0) {
            return $data;
        }
        return false;
    }

    //curl get方式
    public function curl_get($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $data = curl_exec($curl);
        curl_close($curl);
        return $data;
    }

    //curl post方式
    public function curl_post($url, $param)
    {
        $param = json_encode($param, true);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $data = curl_exec($ch);
        return $data;
    }

    //判断是否是企业微信登录
    public function isQyWx()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'wxwork') !== false) {
            return true;
        } else {
            return false;
        }
    }


}